<?php

namespace Cron;

use \Lib\Queue;
use \Zend\Mail;
use \Zend\Mail\Transport\Smtp as SmtpTransport;
use \Zend\Mail\Transport\SmtpOptions;
use \Zend\Mime\Part as MimePart;
use \Zend\Mime\Message as MimeMessage;

final class Email extends \Cron\CronAbstract  {

    protected $options = null;

    /**
     * 目标邮件地址
     *
     * @var string
     */
    protected $send_address = null;

    /**
     * 邮件内容
     *
     * @var string
     */
    protected $send_content = null;

    /**
     * 发送者名称
     *
     * @var string
     */
    protected $send_from    = null;

    /**
     * 目标名称
     *
     * @var string
     */
    protected $send_name    = null;

    /**
     * 邮件主题
     *
     * @var string
     */
    protected $send_subject = null;

    /**
     * 基础URL
     *
     * @var string
     */
    protected $_baseURI = '%s%s';

    public function main() {
        $beginTime = time();

        while (time() - $beginTime < 59){
            $email = Queue::pop('email');

            if(empty($email)){
                sleep(1);
                continue;
            }

            $this->send($email);
        }
    }

    public function exampleChannel($code) {

    }

    /**
     * 发送
     */
    protected function send(array $email){
        $transport = new SmtpTransport();
        $transport->setOptions($this->sendOptions());

        $this->parseContent($email);

        try {
            $transport->send($this->sendMessage());
            $queueModel->setStatus('successed');
        } catch (\Exception $e){
           $queueModel->setStatus('failed');
        }

        $this->reset();
    }

    /**
     * 发送内容
     *
     * @return \Zend\Mail\Message
     * @throws \Exception
     */
    protected function sendMessage(){
        $html = new MimePart($this->send_content);

        //邮件内容格式
        $html->type = "text/html";

        $body = new MimeMessage();
        $body->setParts(array($html));

        $message = new Mail\Message();
        $connection_config = $this->options->getConnectionConfig();

        if(!isset($connection_config['username'])){
           return $message;
        }

        $message->setEncoding('utf-8');
        $message->setBody($body);
        $message->setFrom($connection_config['username'], $this->send_from);

        $message->addTo($this->send_address, $this->send_name);
        $message->setSubject($this->send_subject);

        return $message;
    }

    /**
     * 配置
     */
    protected function sendOptions(){
        if(!$this->options instanceof SmtpOptions){
            $iniOptions = $this->getConfig()->get('resources.smtps');

            if(!$iniOptions) {
                return false;
            }

            $option = $iniOptions->toArray();
            $this->options = new SmtpOptions($option[1]);
        }

        if(!$this->options instanceof SmtpOptions) {
            throw new \Exception("Invalid Options");
        }

        return $this->options;
    }

    /**
     * 解析队列内容　
     *
     * @param array $content
     */
    protected function parseContent(array $content){
        if(empty($content) || !isset($content['channel'])) {
            return false;
        }

        $funcName = strtolower($content['channel']) . 'Channel';

        if(method_exists($this, $funcName)) {
            $address = isset($content['address']) ? $content['address'] : null;
            $username = isset($content['username']) ? $content['username'] : $address;
            $url = isset($content['code']) ? $this->assemble(array('e' => $address, 'c' => $json['channel'], 'i' => $json['code'])) : null;

            $this->send_address = $address;
            $this->send_name    = $username;

            call_user_func_array([$this, $funcName], [$url]);
        }
    }

    /**
     * 组装URL
     *
     * @param array $params
     * @return string
     */
    protected function assemble(array $params = array()) {
        $url = rtrim(trim($this->getConfig()->get('resources.main.url'), '/')) ?: 'http://www.gaoqiapp.com';
        $url .= sprintf($this->_baseURI, (strpos($url, '?') > 0 ? '&' : '?'), http_build_query($params));

        return $url;
    }

    /**
     * 重置　
     */
    protected function reset(){
        $this->send_address = null;
        $this->send_content = null;
        $this->send_name = null;
    }

}
